package com.zpp.gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

//管理游戏房间
@Component
public class RoomManager {
    //存放roomId和房间对象的关系
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();

    //存放用户Id和房间id的关系
      private ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<>();

    public void add(Room room,Integer userId1, Integer userId2){
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }

    public void remove(String roomId,Integer userId1, Integer userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room getRoomByRoomId(String roomId){
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(Integer userId) {
        //1.根据userId获取roomId
        String roomId = userIdToRoomId.get(userId);
        if(roomId == null) {  //如果roomId不存在则返回空
            return null;
        }
        //根据roomId获取Room对象
        return getRoomByRoomId(roomId);
    }
}
